package hr.eon.core.plugins;

import java.io.File;
import java.util.Collection;
import net.xeoh.plugins.base.Plugin;
import net.xeoh.plugins.base.PluginManager;
import net.xeoh.plugins.base.impl.PluginManagerFactory;
import net.xeoh.plugins.base.util.JSPFProperties;
import net.xeoh.plugins.base.util.PluginManagerUtil;
import org.apache.log4j.Logger;

/**
 * Wrapper around JSPF plugin manager.
 * 
 * @author mjovanovic
 * @since 0.0.2
 */
public final class EonPluginManager {

    private static final Logger LOGGER = Logger.getLogger( EonPluginManager.class );

    private static PluginManager pm;
    private static PluginManagerUtil manager;

    private EonPluginManager() {}

    public static void init( ApplicationType type ) {
        LOGGER.info( "Scanning plugins..." );

        final JSPFProperties props = new JSPFProperties();
        String startDir = System.getProperty( "user.dir" );

        File cacheFolder = new File( startDir + "/.eon-cache" );
        if ( !cacheFolder.exists() ) {
            cacheFolder.mkdirs();
        }

        File pluginFolder = new File( startDir + "/plugins" );
        if ( !pluginFolder.exists() ) {
            pluginFolder.mkdirs();
        }

        props.setProperty( PluginManager.class, "cache.enabled", "true" );
        props.setProperty( PluginManager.class, "cache.file", cacheFolder.getPath() + "/plugins.cache" );

        pm = PluginManagerFactory.createPluginManager( props );
        pm.addPluginsFrom( pluginFolder.toURI() );

        manager = new PluginManagerUtil( pm );

        Collection<Plugin> plugins = manager.getPlugins();

        for ( Plugin plug : plugins ) {
            if ( plug instanceof EonPlugin ) {
                EonPlugin plugin = (EonPlugin) plug;

                if ( type.equals( plugin.getPluginType() ) ) {
                    plugin.initialize();
                }
            }
        }

        LOGGER.info( "Scanning plugins completed." );
    }

    public enum ApplicationType {
        CLIENT, SERVER
    }
}
